package day10.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author oldliu
 * @since 1.0
 */
public class AdvanceChatServer {
    public static void main(String[] args) {
        ServerSocket st = null;
        try {
            st = new ServerSocket(9999);
            System.out.println("服务器启动成功，监听在9999端口");
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        while (true) {
            try {
                final Socket s = st.accept();
                new ChatThread(s).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class ChatThread extends Thread {
    private final Socket s;

    public ChatThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        System.out.println(s + "连接成功");
        InputStream in = null;
        try {
            in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            PrintWriter pw = new PrintWriter(out, true);//true表示自动刷新
            //聊天的方式：客户端，服务器回答
            while (true) {
                String ask = br.readLine();//以 \n作为结束标记
                if(ask==null||ask.length()==0)
                    continue;
                String reply = "你说的事情:" + ask + ",朕知道了";
                pw.println(reply);
                if ("byebye".equals(ask))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                System.out.println(s+"退出了。。。");
                s.close();
            } catch (Exception e) {

            }
        }
    }
}
